from rest_framework import serializers
from .models import Tenant
from rest_framework.validators import UniqueValidator
from utils.utils import SetNone

class AddEditBase(serializers.ModelSerializer):
    code = serializers.CharField(
        max_length=12,
        validators=[UniqueValidator(queryset=Tenant.objects.all(), message="租户号已存在")]
    )
    expireTime = serializers.DateTimeField(required=False, allow_null=True)

    class Meta:
        model = Tenant

# 新增
@SetNone()
class AddValidate(AddEditBase):
    class Meta(AddEditBase.Meta):
        exclude = ['id']

# 修改
@SetNone()
class EditValidate(AddEditBase):
    def validate_id(self, val):
        if not Tenant.objects.filter(pk=val).exists():
            raise serializers.ValidationError("编辑对象不存在")
        return val

    class Meta(AddEditBase.Meta):
        fields = '__all__'